//1.获取频道列表数据
async function setChannleList() {
  const res = await axios({
    url: '/v1_0/channels',
  })
  const htmlStr = `<option value="" selected>请选择文章频道</option>` + res.data.channels.map(item => `<option value="${item.id}">${item.name}</option>`).join('')
  console.log(res);
  console.log(htmlStr);
  document.querySelector('.form-select').innerHTML = htmlStr
}
//网站运行后，默认调用一次
setChannleList()

//2.文章封面设置
document.querySelector('.img-file').addEventListener('change', async e => {
  const file = e.target.files[0]
  const fd = new FormData()
  //选择文件并保存到FormData
  fd.append('image', file)
  //单独上传图片并得到图片url网址
  const res = await axios({
    method: 'post',
    url: '/v1_0/upload',
    data: fd

  })
  console.log(res);
  //图片回显
  const imgUrl = res.data.url
  document.querySelector('.rounded').src = imgUrl
  document.querySelector('.rounded').classList.add('show')
  document.querySelector('.place').classList.add('hide')
})
//点击img可以切换封面
document.querySelector('.rounded').addEventListener('click', () => {
  document.querySelector('.img-file').click()
})

//3.发布文章保存
document.querySelector('.send').addEventListener('click', async e => {
  if (e.target.innerHTML !== '发布') return
  const form = document.querySelector('.wrap-right-down ')
  const data = serialize(form, { hash: true, empty: true })
  delete data.id
  console.log(data);
  //自己收集封面图片地址并保存在data中
  data.cover = {
    type: 1,
    images: [document.querySelector('.rounded').src]
  }

  try {
    const res = await axios({
      method: 'post',
      url: '/v1_0/mp/articles',
      data: data
    })
    myAlert(true, '发布成功')
    //重置表单，跳转页面
    form.reset()
    //封面需要手动重置
    document.querySelector('.rounded').src = ''
    document.querySelector('.rounded').classList.remove('show')
    document.querySelector('.place').classList.remove('hide')
    //富文本编辑器重置
    editor.setHtml('')

    setTimeout(() => {
      location.href = '../content/content.html'
    }, 1500)
  } catch (error) {
    console.dir(error);
    myAlert(false, error.response.data.message)
  }
})

  //发布文章页面接收参数判断(共用一套表单)
  ; (function () {
    const paramsStr = location.search;
    const params = new URLSearchParams(paramsStr);
    params.forEach(async (value, key) => {
      if (key === 'id') {
        document.querySelector('.wrap-right-down h4').innerHTML = '修改文章'
        document.querySelector('.send').innerHTML = '修改'
        //获取文章详情数据并回显表单
        const res = await axios({
          url: `/v1_0/mp/articles/${value}`,
        })
        console.log(res);
        //组织需要的数据对象，
        const { channel_id, title, content, id, cover } = res.data;
        const dataObj = {
          channel_id,
          title,
          rounded: cover?.images?.[0], // 防止 cover 可能为空报错
          content,
          id
        };

        //遍历数据对象，映射到页面元素中，快速赋值
        Object.keys(dataObj).forEach(key => {
          if (key === 'rounded') {
            if (dataObj[key]) {
              document.querySelector('.rounded').src = dataObj[key]
              document.querySelector('.rounded').classList.add('show')
              document.querySelector('.place').classList.add('hide')

            }
          } else if (key === 'content') {
            editor.setHtml(dataObj[key])
          } else {
            document.querySelector(`[name=${key}]`).value = dataObj[key]
          }
        })

      }
    })
  })()

//编辑保存文章
document.querySelector('.send').addEventListener('click', async e => {
  if (e.target.innerHTML !== '修改') return
  //修改文章逻辑
  const form = document.querySelector('.wrap-right-down')
  const data = serialize(form, { hash: true, empty: true })
  console.log(data);
  //调用编辑文章接口，保存信息到服务器
  try {
    const res = await axios({
      method:'PUT',
      url: `/v1_0/mp/articles/${data.id}`,
      data: {
        ...data,
        cover:{
          type: document.querySelector('.rounded').src ? 1 : 0,
          images:[document.querySelector('.rounded').src]
        }
      }
    })
    console.log(res);
    myAlert(true,'修改文章成功')
  } catch (error) {
    myAlert(false,error.response.data.message)
  }
})
